# encoding=utf8
'''
Created on Oct 28, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
import json

from django.http.response import HttpResponse

from app_info.models import App
from utils import JsonResponse
from ads_info.models import AdsInfo, AdsUnit
from django.utils import timezone
import time
from django.views.decorators.csrf import csrf_exempt


def get_app_name(req):
    try:
        res = App.objects.get(id=req.REQUEST.get('id')).__unicode__()
    except Exception, e:
        print e
        res = '???'
    return HttpResponse(json.dumps({'res': res}), mimetype='application/json')


def str_is_date(input):
    try:
        time.strptime(input, '%Y-%m-%d')
        return True
    except ValueError:
        return False


def get_ads(req):
    start_date = req.REQUEST.get('startDate')
    end_date = req.REQUEST.get('endDate')
    if not start_date:
        return JsonResponse({'msg': "'startDate' is required.", 'code': 0})
    if not str_is_date(start_date):
        return JsonResponse({'msg': "date format: 'YYYY-MM-DD'", 'code': 0})
    if end_date and not str_is_date(end_date):
        return JsonResponse({'msg': "date format: 'YYYY-MM-DD'", 'code': 0})
    platform = req.REQUEST.get('platform')
    if not platform in ('android', 'ios'):
        return JsonResponse({'msg': "platform must be 'android' or 'ios'.",
                             'code': 0})
    ads_info = AdsInfo.objects.filter(create_time__gte=start_date,
        app__platform='I' if platform == 'ios' else 'A', status='F')
    if end_date:
        if end_date == start_date:
            year, month, day = end_date.split('-')
            ads_info = ads_info.filter(create_time__year=year, create_time__month=month,
                create_time__day=day)
        else:
            ads_info = ads_info.filter(create_time__lte=end_date)
    app_ids = list(set(ads_info.values_list('app', flat=True)))
    data = []
    for i in app_ids:
        app = App.objects.get(id=i)
        rtn = {'appCode': app.prj_code, 'bundleID': app.get_full_bundle_id(),
               'platform': app.get_platform_display()}
        app_ads_info = ads_info.filter(app_id=i)
        for n in app_ads_info:
            units = n.adsunit_set.filter(activation='P')
            units.update(latest_get_time=timezone.localtime(timezone.now()))
            for u in units:
                if not u.first_get_time:
                    u.first_get_time = timezone.localtime(timezone.now())
                    u.save()
                rtn.update({str(u.unit): u.value})
        if len(rtn.keys()) == 3:
            continue
        data.append(rtn)
    return JsonResponse({'code': 1, 'msg': 'success', 'apps': data,
        'startDate': start_date, 'endDate': end_date or timezone.localtime(timezone.now()).date()})


@csrf_exempt
def activate_ads(req):
    '''
    mark if the ads id activated.
    '''
    data = req.REQUEST.get('data')
    try:
        data = json.loads(data)
        apps = data['apps']
    except Exception, e:
        print e
        return JsonResponse({'msg': "parameter format invalid.", 'code': 0})
    for app in apps:
        for k in app.keys():
            if k in ['bundleID', 'appCode', 'platform']:
                continue
            unit = AdsUnit.objects.filter(value=k)[:1]
            if not unit:
                continue
            unit = unit[0]
            if app.get(k):
                unit.activation = 'A'
            else:
                unit.fail_count += 1
                if unit.fail_count >= 3 and (unit.latest_get_time - unit.first_get_time).days >= 3:
                    unit.activation = 'F'
            unit.save()
    return JsonResponse({'msg': 'success', 'code': 1})


@csrf_exempt
def check_ads(req):
    """
    check ads is exist
    """
    bundle_id = req.REQUEST.get('bundle_id')
    ads_id = req.REQUEST.get('ads_id')
    bundle_id_act = ''
    print ads_id
    # get bundle id 
    try:
        adsunit = AdsUnit.objects.get(value=ads_id)
        bundle_id_act = adsunit.info.app.get_full_bundle_id()
    except Exception, e:
        print e
    try:
        bundle_id_prefix = bundle_id[:0 - len(bundle_id.split('.')[2])]
        apps = App.objects.filter(bundle_id_prefix=bundle_id_prefix, bundle_id_suffix=bundle_id.split('.')[2])
        if not apps:
            return JsonResponse({'msg': 'app not exist.', 'code': 0, 'bundle_id_act': bundle_id_act})
        ads_infos = AdsInfo.objects.filter(app__in = apps, status='F')
        if not ads_infos:
            return JsonResponse({'msg': 'Activated AdsUnit not exist.', 'code': 0, 'bundle_id_act': bundle_id_act})
    except Exception, e:
        print e
        return JsonResponse({'msg': "bundle_id invalid.", 'code': 0, 'bundle_id_act': bundle_id_act})
    for ads_info in ads_infos:
        print ads_info.app.app_name
        units = AdsUnit.objects.filter(info=ads_info, status='A')
        for unit in units:
            if unit.value == ads_id:
                return JsonResponse({'msg': 'Accept.', 'code': 1, 'bundle_id_act': bundle_id_act})
    return JsonResponse({'msg': 'AdsUnit not exist.', 'code': 0, 'bundle_id_act': bundle_id_act})